<template>
  <el-card class="box-card">
    <div>
      <!-- 搜索框 -->
      <el-form
        ref="searchData"
        :inline="true"
        :model="searchData"
        class="demo-form-inline"
      >
        <el-form-item label="搜索" style="width: 23%">
          <el-input
            v-model="searchData.username"
            clearable
            maxlength="64"
            placeholder="账号/姓名/权限/用户名/手机号/邮箱"
            style="width: 120%"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            icon="el-icon-search"
            type="primary"
            @click="getDataListBySearch"
          >查询
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="openInsertWindow"
          >新增
          </el-button>
        </el-form-item>
        <el-form-item v-if="multipleSelection.length>0">
          <el-button @click="toggleSelection()"> 取消选择</el-button>
        </el-form-item>
        <el-form-item v-if="multipleSelection.length>0">
          <el-button type="danger" @click="deleteSelection()">
            批量删除
          </el-button>
        </el-form-item>
        <el-form-item v-if="multipleSelection.length>0">
          <el-button type="primary" @click="exportCheck()">
            导出选择
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="exportAll()">
            导出全部
          </el-button>
        </el-form-item>
      </el-form>
      <!-- 角色数据表单 -->
      <el-table
        ref="multipleTable"
        :data="dataList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="40"></el-table-column>
        <el-table-column label="编号" prop="userId" width="50">
        </el-table-column>
        <el-table-column label="账号" prop="account" width="110">
        </el-table-column>
        <el-table-column label="用户名" prop="username" width="110">
        </el-table-column>
        <el-table-column label="用户姓名" prop="name" width="130">
        </el-table-column>
        <el-table-column label="账号状态" prop="status" width="80">
          <template v-slot="scope">
            <span>{{ scope.row.status === 1 ? "正常" : "禁用" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="账号权限" prop="roleName" width="100">
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="180">
        </el-table-column>
        <el-table-column label="邮箱" prop="email" width="130">
        </el-table-column>
        <el-table-column label="手机号码" prop="mobile" width="130">
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button
              size="mini"
              type="warning"
              @click="deleteUser(scope.row)"
            >删除
            </el-button>
            <el-button
              v-if="scope.row.status === 1"
              size="mini"
              type="danger"
              @click="changeUserStatus(scope.row)"
            >禁用
            </el-button>
            <el-button
              v-if="scope.row.status !== 1"
              size="mini"
              type="success"
              @click="changeUserStatus(scope.row)"
            >激活
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 新增按钮打开的页面 -->
      <el-dialog :visible.sync="insertWindow" title="新增用户">
        <el-form :model="insertData">
          <el-form-item label="用户名" label-width="120px">
            <el-input
              v-model="insertData.username"
              autocomplete="off"
              placeholder="账号"
              style="width: 80%"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" label-width="120px">
            <el-input
              v-model="insertData.password"
              autocomplete="off"
              placeholder="密码"
              style="width: 80%"
              type="password"
            ></el-input>
          </el-form-item>
          <el-form-item label="姓名" label-width="120px">
            <el-input
              v-model="insertData.name"
              autocomplete="off"
              placeholder="姓名"
              style="width: 80%"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色" label-width="120px">
            <el-select v-model="insertData.roleId" placeholder="请选择">
              <el-option
                v-for="{roleId,roleName} in roles"
                :key="roleId"
                :label="roleName"
                :value="roleId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="邮箱" label-width="120px">
            <el-input
              v-model="insertData.email"
              autocomplete="off"
              placeholder="邮箱"
              style="width: 80%"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号码" label-width="120px">
            <el-input
              v-model="insertData.mobile"
              autocomplete="off"
              placeholder="手机号码"
              style="width: 80%"
            ></el-input>
          </el-form-item>
          <el-form-item label="描述信息" label-width="120px">
            <el-input
              v-model="insertData['remark']"
              style="width: 80%"
              type="textarea"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="insertWindow = false;">取 消</el-button>
          <el-button type="primary" @click="insertUser()">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 页号 -->
      <el-pagination
        :current-page="pageIndex"
        :page-size="pageSize"
        :page-sizes="pageSizes"
        :total="totalPage"
        layout="total ,sizes,prev,pager,next,jumper"
        style="margin-top: 30px"
        @size-change="sizeChangeHandle"
        @current-change="CurrentChangeHandle"
      >
      </el-pagination>
    </div>
  </el-card>
</template>
<script>
export default {
  name: "SysUser",
  data() {
    return {
      //数据参数
      searchData: {},//搜索数据
      insertData: {},//新增数据

      //集合参数
      dataList: [], //页面展示的数据集合
      roles: [], //角色列表
      multipleSelection: [], //批量操作数组

      //页号参数
      pageIndex: 1,
      pageSize: 5,
      pageSizes: [],
      totalPage: 0,
      begin: 0,
      end: this.pageSize - 1,

      //窗口显示参数
      insertWindow: false,

      //其他
      access: sessionStorage.getItem("roleId"),
      username: sessionStorage.getItem("username"),
      dataListFrom: "getDataList",//当前数据来源于搜索还是全局
    };
  },
  methods: {
    //改变数组大小
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.SizeOrCurrentChangeAfter();
    },
    //改变当前页号
    CurrentChangeHandle(val) {
      this.pageIndex = val;
      this.SizeOrCurrentChangeAfter();
    },
    //在更改数组大小或者页号前，判断数据来源
    SizeOrCurrentChangeAfter() {
      if (this.dataListFrom === "getDataList")
        this.getDataList();
      else this.getDataListBySearch();
    },

    //导出全部
    exportAll() {
      this.export([])
    },
    //导出所选
    exportCheck() {
      this.export(this.multipleSelection)
    },
    //导出方法
    export(item) {
      this.$http.post("/export/user", item).then(res => {
        this.$exportExcel(res)
      })
    },
    //表格被点击，添加data数组数据
    handleSelectionChange(val) {
      this.multipleSelection = []
      val.forEach(item =>
        this.multipleSelection.push(item.userId)
      )
    },
    //清空选中的集合
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },


    //分页操作
    cutDataList(res) {
      const data = this.$cutPageDataList(res)
      this.dataList = data.dataList
      this.totalPage = data.totalPage
    },

    //查询所有数据
    getDataList() {
      this.dataListFrom = "getDataList";
      const pageInfo = this.$getPageInfo(this.pageSize, this.pageIndex)
      this.$http.post("/user/getPageVo", pageInfo).then((res) => {
        this.cutDataList(res);
      });
    },
    //查询数据
    getDataListBySearch() {
      this.dataListFrom = "getDataListBySearch";
      const data = {
        userBo: this.searchData,
        pageBo: this.$getPageInfo(this.pageSize, this.pageIndex)
      }
      this.$http.post("/user/getPageVo/search", data).then((res) => {
        this.cutDataList(res);
      });
    },
    //获取角色信息
    getRoleList() {
      this.$http.post("/role/getList/roleKind").then((res) => {
        this.roles = res;
      });
    },

    //打开添加窗口
    openInsertWindow() {
      this.insertWindow = true;
      this.insertData = {};
    },

    //删除用户
    deleteUser(item) {
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const data = {
          userId: item["userId"],
          pageBo: this.$getPageInfo(this.pageSize, this.pageIndex)
        }
        // 表示处理的是 删除操作
        this.$http.post("/user/delete", data).then((res) => {
          if (res != null) {
            this.cutDataList(res)
          }
        });
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除",
        });
      });
    },
    //新增页面的确认键
    insertUser() {
      const data = {
        userBo: this.insertData,
        pageBo: this.$getPageInfo(this.pageSize, this.pageIndex)
      }
      this.$http.post("/user/insert", data).then((res) => {
        if (res != null) {
          this.insertWindow = false; //关闭窗口
          this.cutDataList(res)
        }
      });
    },
    //改变账号激活/禁用状态
    changeUserStatus(row) {
      if (this.access < row.access || row.username === this.username) {
        const data = {
          bo: row,
          pageBo: this.$getPageInfo(this.pageSize, this.pageIndex)
        }
        this.$http.post("/user/ChangeStatus", data).then((res) => {
          if (row.username === this.username) {
            this.$message.warning("您已将账号禁用,请联系管理员或许你可以重新注册一个账号")
            // 清空存储的Token信息
            sessionStorage.clear();
            // 然后跳转到登录页
            this.$router.push("/");
          }
          this.cutDataList(res);
        });
      } else {
        //当前用户无权限修改此用户的此用户的账号状态
        this.$message.warning("当前用户无法修改" + row.roleName + "的账号状态")
      }
    },
    //批量删除
    deleteSelection() {
      this.$confirm("是否确认全部删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const data = {
            ids: this.multipleSelection,
            pageBo: this.$getPageInfo(this.pageSize, this.pageIndex)
          }
          this.$http.post("/user/deleteList", data).then((res) => {
            this.cutDataList(res)
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        })
    },

    //初始化页号
    setPageSize() {
      this.pageSizes = this.$getPageSize()
      this.pageSize = this.pageSizes[0]
    }
  },
  mounted() {
    this.setPageSize()
    this.getDataList();
    this.getRoleList();
  },
};
</script>
